#include "Assistant.h"
#include "memdb/error/MemdbError.h"

namespace memdb {
namespace impl {
namespace assistant {

static unsigned int digit_num(unsigned int value) {
  unsigned int count = 1;
  for (;;) {
    if (value < 10) return count;
    if (value < 100) return count + 1;
    if (value < 1000) return count + 2;
    if (value < 10000) return count + 3;
    value /= 10000;
    count +=4;
  }
}

static std::string genOrderNo(unsigned int seq) {
  unsigned int digitLen = digit_num(seq);
  if (digitLen < 6) {
    return std::string("00").append(std::string(6 - digitLen, '0')).append(std::to_string(seq));
  }
  return std::string("00").append(std::to_string(seq));
}

static std::string genOffsetFlag(unsigned int seq) {
  unsigned int ret = seq % 3;
  switch (ret) {
    case 0:
      return "0";
    case 1: 
      return "1";
    default:
      return "2";
  }
}

static std::string genOrderRecord(unsigned int seq) {
  return std::string("{\"orderNo\":\"").append(genOrderNo(seq)).append(std::string("\",\"offsetFlag\":\""))
          .append(genOffsetFlag(seq)).append(std::string("\"}"));
}

std::error_code Assistant::fillData(ITable * table, size_t size) {
  if (table) {
    for(unsigned int i = 0; i < size; ++i) {
      table->insert(genOrderNo(i), genOrderRecord(i));
    }
    return memdb::error::ok;
  }
  return memdb::error::error;
}

}//namespace assistant
}//namespace impl
}//namespace memdb
